package com.jingwu.nacos;

import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class NacosConfigWriterApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosConfigWriterApplication.class, args);
    }

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${nacos.server-addr}")
    private String serverAddr;

    @Value("${nacos.group}")
    private String group;

    @RestController
    public class TestController {

        @SneakyThrows
        @PostMapping("/test/write")
        public String write(@RequestBody Rule rule) {
            ConfigService configService = ConfigFactory.createConfigService(serverAddr);
            String content = objectMapper.writeValueAsString(rule);
            configService.publishConfig(group + ":" + "route", group, content);
            return content;
        }

    }

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }

    @Data
    public static class Rule {
        private String name;
        private String routerId;
        private String path;
    }

}
